<!--
 * @Author: panda-hbd 1511539537@qq.com
 * @Date: 2022-11-18 19:12:09
 * @LastEditors: 姚贤通 10254465+yao-xiantong@user.noreply.gitee.com
 * @LastEditTime: 2022-11-22 18:09:51
 * @FilePath: \text-online-system4\src\views\CreateNewWork.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="box">
    <div class="head">
      <ul>
        <li @click="this.$router.back()">
          <el-icon>
            <CloseBold />
          </el-icon>
        </li>
        <li style="color: #ccc">|</li>
        <li>新建试卷</li>
      </ul>
      <div class="btns">
        <!-- <el-button type="primary">保存并预览</el-button> -->
        <el-button type="primary" @click="addPaper">保存</el-button>
        <el-button type="primary" plain @click="this.$router.back()"
          >取消</el-button
        >
      </div>
    </div>

    <div class="main">
      <div class="container">
        <div class="top">
          <div style="display: flex;"><h2>作业标题：{{this.$route.query.formName}}</h2></div>
          <p>作业介绍：【{{this.$route.query.formRegion}}】</p>
        </div>
        <div class="paperInfo">
          <div class="left">
            <div class="leftTop">
              <div>
                <p style="color: var(--blueColor2); font-size: 18px">
                  试卷信息
                </p>
                
                <span class="del" style="display: flex;align-items: center;" @click="deleteRequeseList">
                  <el-icon> <Delete /> </el-icon>删除
                </span>
              </div>
              <div>
                <el-button type="primary">
                  <el-icon> <DocumentAdd /> </el-icon>批量导入
                </el-button>
                <el-button type="primary" @click="openCreateTest"
                  >+ 添加习题</el-button
                >
                <!-- 添加题目弹出框 -->
                <el-dialog v-model="dialogTableVisible" title="添加习题"  :destroy-on-close="true">
                  <!-- 选择题型 -->
                  <div class="item">
                    <label for="" style="margin-right:2.25rem ;">题型</label>
                    <el-select
                      v-model="questionType"
                      class="m-2"
                      placeholder="单选题"
                      size="large" 
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                  <!-- 题干 -->
                  <div class="item">
                    <div><label for="" style="margin-right:2.25rem ;">题干</label></div>
                    <!-- 备注：题干的值来自MyEditor组件的自定义事件change -->
                   <div class="editor"> <MyEditor @change="getEditorScam"></MyEditor></div>
                  </div>
                  <!-- 单选题 -->
                 <template v-if="questionType=='单选题'">
                  <!-- 单选题默认渲染4个选项 -->
                  
                  <div class="item"  v-for="(editor,i) in optionCount" :key="editor">
                    <div><input type="radio" name="1" @change="checkGiveSingleData(i)"  id=""><label for="">选项{{i+1}}</label><br><span class="span" style="color:green;display:none">正确答案</span></div>
                    <div class="editor"><textarea v-model="readyWorkData.option[i]"  @change="change" name="" id="" cols="96" rows="3"></textarea></div>
                    <div><el-icon @click="reduceOptionCount(i)"><RemoveFilled /></el-icon></div>
                  </div>
                 </template>

                 
                 <!-- 多选题 -->
                 <template v-if="questionType=='多选题'">
                  <div class="item"  v-for="(editor,i) in optionCount" :key="editor">
                    <div><input type="checkbox"  id=""  @change="checkGiveData($event,i)"><label for="">选项{{i+1}}</label><br><span class="span" style="color:green;display:none">正确答案</span></div>
                    <div class="editor"><textarea v-model="readyWorkData.option[i]"  @change="change" name="" id="" cols="96" rows="3"></textarea></div>
                    <div><el-icon @click="reduceOptionCount(i)"><RemoveFilled /></el-icon></div>
                  </div>
                 </template>
                 <!-- 判断题 -->
                 <template v-if="questionType=='判断题'">
                  <div class="item" style="display:flex; align-items: center;">
                    <div><label for="">答案</label></div>
                    <div class="editor">
                      <input type="radio" name="2" id="" style="margin-left:1rem;" @click="checkTrue(1)"><el-icon style="color:green;"><Select /></el-icon>正确
                      <input type="radio" name="2" id="" style="margin-left:1rem;" @click="checkTrue(0)"><el-icon style="color:red;"><CloseBold /></el-icon>错误
                    </div>
                  </div>
                 </template>
                
                  <div class="item" v-if="questionType=='单选题'||questionType=='多选题'" >
                    <div class="addOption">
                      <p @click="addOptionCount"><el-icon><Plus /></el-icon></p>
                      <p>添加选项</p>
                    </div>
                  </div>
                  <!-- 设置每题的分值 -->
                  <div class="item">
                    <div><label for="">本题分值</label></div>
                    <!-- change事件为当分数改变时触发handleSubjectScoreChange函数 -->
                    <el-input-number v-model="subjectScore" :min="1" :max="100" controls-position="right" size="large"
                      @change="handleSubjectScoreChange" />
                  </div>
                 <!-- 答案解析 -->
                 <div class="item">
                    <div><label for="">答案解析</label></div>
                    <div >
                      <input type="checkbox" name="" id="" v-model="addAnalysis"><i style="margin-left: 0.5rem;color: var(--blueColor2);">添加答案解析</i>
                    </div>
                  </div>
                  <!-- 答案解析的文本输入框 -->
                  <div v-if="addAnalysis" style="margin-left: 3rem;margin-top: 1rem;">
                    <div class="editor" >
                      <textarea placeholder="请输入答案解析..." v-model="readyWorkData.analysis"  id="" cols="96" rows="3" style="margin-left:1.2rem;"></textarea>
                  </div>
                  </div>
                  <!-- 底部按钮 -->
                  <div class="item">
                    <el-button type="primary" plain @click="cancelQuestion">取消</el-button>
                    <el-button type="primary" @click="createNewQuestion">保存</el-button>
                  </div>
                </el-dialog>
                <!-- 弹出框end -->
              </div>
            </div>
            <div class="leftCenter">
              <!-- 习题为空时显示 -->
              <div v-if="false">暂无习题</div>
              <!-- 习题不为空时显示 -->
              <div v-if="true">
                <ul
                  v-infinite-scroll="load"
                  class="infinite-list"
                  style="overflow: auto"
                >
                <li v-for="(work,index) in workDataList" :key="i" class="infinite-list-item">
                    <div class="subject">
                      <div style="margin-right:1rem ;">
                        <input type="checkbox" name="" id="" @click="addRemoveList($event,index)">
                      </div>
                      <template v-if="(work.type == 1 || work.type == 2)">
                        <div>
                          <div class="type">
                        <h4>{{work.type == 1 ? '单选题':'多选题'}}</h4>
                        <span><i>{{work.score}}</i>分</span>
                      </div>
                        </div>
                       <!-- </div> -->
                      <div class="subject-text " ref="stems"  :data="work.stem">
                     
                      </div>
                      <div class="answer">
                        <ul>
                          <li v-for=" (item,index) in work.options.split(' ') ">
                            <template v-if="work.result.includes(item)">
                              
                                <i style="background-color: #67c23a;">{{String.fromCharCode(65+index)}}</i>
                              
                            </template>
                            <template v-else>
                              
                              <i>{{String.fromCharCode(65+index)}}</i>
                            
                          </template>
                            
                            {{item}}</li>
                        </ul>
                      </div>
                      <div class="eachScore">
                        <span>本题分值</span>
                        <el-input-number
                          v-model= work.score
                          :min="1"
                          :max="10"
                          @change="handleChange"
                        />
                      </div>
                      </template>
                      <template v-if="(work.type == 3)">
                        <div>
                          <div class="type">
                        <h4>{{'判断题'}}</h4>
                        <span><i>{{work.score}}</i>分</span>
                      </div>
                        </div>
                        <br>
                        <template  v-if="(work.result == '正确')">
                          <div style="display: flex;align-items: center;">
                            <el-icon style="color: green;"><Select /></el-icon>&nbsp;&nbsp;<p ref="stems" :data="work.stem"></p>
                          </div>
                        </template>
                        <template  v-if="(work.result == '错误')">
                          <div style="display: flex;align-items: center;">
                            <el-icon style="color: red;"><CloseBold /></el-icon>&nbsp;&nbsp;<p ref="stems" :data="work.stem"></p>
                          </div>
                        </template>
                        <div class="eachScore">
                        <span>本题分值</span>
                        <el-input-number
                          v-model= work.score
                          :min="1"
                          :max="10"
                          @change="handleChange"
                        />
                      </div>
                      </template>
                     


                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div class="right">
            <h3>习题列表</h3>
            <ul>
              <li><span>单选题</span><i>{{singleChoiceSum}}</i></li>
              <li><span>多选题</span><i>{{multipleChoiceSum}}</i></li>
              <li><span>判断题</span><i>{{judgmentalChoiceSum}}</i></li>
            </ul>
            <h3>总分</h3>
            <ul>
              <li><span>总分：</span><i>{{scroSum}}分</i></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { createWebSocketStream } from 'ws';
import MyEditor from '../components/MyEditor.vue'
import paper from '../api/paper'
import question from '../api/question'

export default {
  name: "CreateNewWork",
  components:{
    MyEditor,

  },
  data() {
    return {
      isEdit:0,
      optionList:['单选题','多选题','判断题','填空题','主观题'],
      optionCount:4,
      dialogTableVisible: false,//element自带的属性
      count: 8,//模拟题目数量循环渲染
      questionType:'单选题',//题目类型，默认单选
      addAnalysis:false,//是否添加解析的复选框，默认不勾选
      subjectScore:0,//题目的分数
      //options是题目类型的数据
      workDataList:[],
      
      readyWorkDataList:[],

      readyWorkData:{
        score:'',
        stem:'',
        option:[],
        result:'',
        type:'',
        analysis:''
      },
      singleCount:0,//单选题总数
      doubleCount:0,//多选
      judgeCount:0,//判断
      paperData:{
        teacherId:1,
        paperName:this.$route.query.formName,//试卷名
        instruction:this.$route.query.formRegion,//试卷介绍
        questions: 0,//题目总数
        score:0,//总分
        upDataDate:'',
        createDate:'',
      },

      createPAper:true,

      removeList:[],
      readyResult:[],
      readySingleResult:'',
      chooseResult:'',
      options:[
  {
    value: '单选题',
    label: '单选题',
  },
  {
    value: '多选题',
    label: '多选题',
  },
  {
    value: '判断题',
    label: '判断题',
  }],


  
    };
  },

  mounted() {

    if(this.$route.query.paperId != 'null'){
      this.isEdit = 1;
      console.log(this.$route.query.paperId);
      question.getAllQuestionsByPaperId({
        paperId:this.$route.query.paperId
      }).then((res)=>{
        
        if(res.code == 1 && res.data)
           this.workDataList = res.data
        console.log("题目数据",this.workDataList);
      })
    }
      
       this.initStem()
      
  },

  updated(){
    this.initStem()
  },

  computed:{


    scroSum(){
      //总分统计
      var sum = 0;
      if(this.workDataList != undefined){
         for(let i = 0;i < this.workDataList.length;i++){
        
        sum += this.workDataList[i].score;
      }
      this.paperData.score = sum
      }
     
      return sum;
    },
    singleChoiceSum(){
      //单选题数量统计
      var sum = 0;
      console.log('workDataList' + this.workDataList);
      if(this.workDataList != undefined){
      for(let i = 0;i < this.workDataList.length;i++){
        if(this.workDataList[i].type == 1){
          sum ++
        }
      }
      this.singleCount = sum
    }
      return sum;
    },
    multipleChoiceSum(){
      //多选题数量统计
      var sum = 0;
      if(this.workDataList != undefined){
      for(let i = 0;i < this.workDataList.length;i++){
        if(this.workDataList[i].type == 2){
          sum ++
        }
      }
      this.doubleCount = sum
    }
      return sum;
    },
    judgmentalChoiceSum(){
      //判断题数量统计
      var sum = 0;
      if(this.workDataList != undefined){
      for(let i = 0;i < this.workDataList.length;i++){
        if(this.workDataList[i].type == 3){
          sum ++
        }
      }
      this.judgeCount = sum
    }
      return sum;
    },
    
    
  },

  methods: {
    cancelQuestion(){
      //退出弹窗
      this.dialogTableVisible = false
    },
    addPaper(){ 
      this.paperData.questions = this.singleCount + this.doubleCount + this.judgeCount
      if(this.paperData.questions == 0){
        alert("题目列表不能为空！！！！")
      }else{
        console.log(this.paperData);
      if(this.isEdit == 0){
          paper.addNewPaper({
            questionList:this.workDataList,
            paperObject:this.paperData,
            paperId:"null"
          }).then((res)=>{

          })
      }else{
        paper.addNewPaper({
            questionList:this.workDataList,
            paperObject:this.paperData,
            paperId:this.$route.query.paperId
          }).then((res)=>{

          })
      }
      this.$router.push("/index/files")
      }
     
      
    },

    deleteRequeseList(){
      for(let i = 0;i < this.removeList.length;i++){
        this.workDataList.splice(this.removeList[i],1)
      }
      this.removeList = []
    },
    addRemoveList(e,index){
      if(e.target.checked==true){
        this.removeList.push(index)
      }else{
        this.removeList.splice(index,1)
      }
    },
    checkTrue(choose){
      //弹窗判断题的答案
      if(choose == 1){
        this.chooseResult = "正确"
      }else{
        this.chooseResult = "错误"
      }
    },

    initStem(){

      if( this.$refs.stems)
      this.$refs.stems.forEach(val=>{
             val.innerHTML = val.getAttribute('data')
         })
    },
  
    reduceOptionCount(index){//减少选项总数
      if(this.optionCount >= 3){
        this.readyWorkData.option.splice(index,1);
        
        this.optionCount --
      }else{
        alert("选项至少有两个")
      }
    },
    addOptionCount(){
      //添加选项数量
      if(this.optionCount < 5){
        this.optionCount ++
      }else{
        alert("选项总数最多只能有五个")
      }
    },
    change(){
      //  console.log(this.option)
    },

    checkGiveData(e,index){
      console.log(index);
      if(e.target.checked==true){
        this.readyResult.push(this.readyWorkData.option[index])
      }else{
        this.readyResult.splice(this.readyResult.indexOf(this.readyWorkData.option[index]),1);
      }
    },
    checkGiveSingleData(index){
      this.readySingleResult = this.readyWorkData.option[index]
    },
    
    load() {
      this.count += 0;
    },
    rightAnswer(e){
      var span = e.target.nextElementSibling.nextElementSibling.nextElementSibling
      // console.log(e.target.nextElementSibling.nextElementSibling.nextElementSibling);
      span.style.display = 'block'
    },
    // 底部的保存按钮触发的函数
    createNewQuestion(){

      
      //把输入的数据存入readyWorkData集合中  
      this.readyWorkData.type = this.questionType;

      if(this.readyWorkData.type == "单选题"){
        this.readyWorkData.result = this.readySingleResult
        console.log(this.readyWorkData.result );

      }else if(this.readyWorkData.type == "多选题"){
        
        this.readyWorkData.result = this.readyResult.map(val=>{
          return val.replace(/\s+/i,"")
      }).join(" ")
        console.log(this.readyWorkData.result);
      }else if(this.readyWorkData.type == "判断题"){
        console.log("判断题");
        this.readyWorkData.result = this.chooseResult;
      }
      
      this.readyWorkData.score = this.subjectScore;
      
      
      this.readyWorkData.option1 = this.readyWorkData.option.map(val=>{

          return val.replaceAll(/\s+/ig,"")
      }).join(" ")

      if(this.readyWorkData.result == ''){
        alert('结果不能为空!!')
      }else if(this.readyWorkData.type != "判断题" && this.readyWorkData.option1 == ''){
        alert("请填写选项！！")
      }else{
        let data={};
      data.result = this.readyWorkData.result.replaceAll(/\s+/ig,'');
      data.type =  this.optionList.findIndex(val=>val==this.readyWorkData.type) + 1;
      data.score =this.readyWorkData.score;
      data.stem =this.readyWorkData.stem;
      data.options =this.readyWorkData.option1;
      data.analysis =this.readyWorkData.analysis;


      this.workDataList.push(data);
      

      console.log(this.workDataList);
      
      
     
      this.dialogTableVisible = false
      this.clearAll();
      }

      
      
    },
    openCreateTest(){
      var stem = ''
      this.dialogTableVisible = true
      this.getEditorScam(stem)
      // this.readyResult = ''
      // this.questionType = ''
      // this.optionCount=4
    },
    clearAll(){
      this.readyWorkData.result = ''
      this.readyWorkData.type = ''
      this.readyWorkData.score = ''
      this.readyWorkData.stem = ''
      this.readyWorkData.option = []
      this.readyWorkData.analysis = ''
      //his.readyWorkData={};
      this.optionCount = 4;
    },
    //获取MyEditor组件输入框的内容，即题干（富文本，带html标签）
    getEditorScam(value){
      this.readyWorkData.stem = value;
    },
    
  
   
  },


};
</script>

<style scoped>
.box {
  width: 100%;
  flex-direction: column;
}
/* 头部 */
.head {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 4rem;
  border-bottom: 1px solid var(--blueColor5);
  padding: 0 2rem;
}

.head ul {
  display: flex;
  align-items: center;
}

.head ul li {
  color: var(--balckColor);
  padding: 0 0.3rem;
  line-height: 3rem;
}

.btns {
  line-height: 4rem;
}

/* 主体内容 */
.main {
  background-color: #efefef;
  padding: 0;
  height: 90.8%;
  padding-top: 1rem;

}
.container {
  width: 80%;
  margin: 0 auto;
}
.top {
  background-color: #fff;
  padding: 0.5rem 1rem;
  margin-bottom: 1rem;
}

.top p {
  font-size: 0.875rem;
  margin: 0.5rem auto;
}
.paperInfo {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.left {
  width: 64.5%;
  height: 32rem;
  padding: 0.5rem 1rem;
  background-color: #fff;
}

.leftTop {
  display: flex;
  justify-content: space-between;
  padding-bottom: 1rem;
  border-bottom: 1px solid #ccc;
}

.subjectBox {
  overflow: hidden;
}


.leftCenter {
  width: 100%;
  height: 80%;
  /* overflow: hidden; */
  /* background-color: pink; */
}

.del {
  color: #a9a9a9;
}

.all,
.del {
  margin-left: 1rem;
  font-size: 0.875rem;
  margin-top: 0.5rem;
}

.right {
  width: 34%;
  /* height: 200px; */
  background-color: #fff;
  padding: 1rem;
}
.right ul li{
  padding: 0.5rem 1rem;
  margin: 0.5rem 0;
  background-color: var(--blueColor6);
}

/* 题目项 */
.subject {
  width: 100%;
  padding: 1rem 0;
  border-bottom: 1px dotted #ccc;
  padding-left: 4rem;
}

.type {
  display: flex;
  align-items: center;
  /* font-size: 0.875rem; */
  border-left: 4px solid var(--blueColor2);
  padding-left: 0.5rem;
}

.type h4 {
  font-size: 1rem;
  font-weight: 600;
  color: var(--blueColor2);
}

.type span {
  font-size: 0.875rem;
  color: rgb(106, 104, 104);
  margin-left: 0.6rem;
}

.subject-text {
  margin: 1rem 0;
}

.answer ul li {
  display: flex;
  align-items: center;
  margin: 0.5rem 0;
  color: rgba(0, 0, 0, 0.769);
  font-size: 0.875rem;
}

.answer ul li i {
  display: block;
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  color: var(--blueColor2);
  border: 1px solid var(--blueColor2);
  margin-right: 1rem;
  font-size: 1.2rem;
  text-align: center;
  line-height: 2rem;
}

.eachScore {
  margin-top: 1rem;
}

/* 无限下拉 */
.infinite-list {
  height: 437px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  /* height: 50px; */
  /* background: var(--el-color-primary-light-9); */
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}



.item{
  display: flex;
  justify-content:flex-start;
  margin-top: 1rem;
}
.item label{
  margin-right: 1rem;
}
.item .el-icon{
  color: red;
  font-size: 1.5rem;
}
textarea{
  outline: none;
  padding: 0.3rem;
  resize: none;
  width: 100%;
}
.editor{
  width: 630px;
}
/* 添加选项按钮start */
.addOption{
  width: 100%;
  text-align: center;
}
.addOption .el-icon{
  font-size: 2rem;
  color:#67c23a;
}
.addOption p{
  color: rgb(146, 145, 145);
}
/* 添加选项按钮end */
</style>
